25

Build Your Own Game—Tic Tac Toe

25

Sub TicTacToe()

Dim sbox(3, 3)

' sbox stores the current value

' *** initialize

WinTag = Array(0, 30, 238, 506, 627, 935, 1001, 1495, 7429)

If UserForm1.Controls("TextBox10") <> "" Then

UserForm1.Controls("TextBox10") = "Click Play to Start"

Else

A = ExamineEachFormCell(EmptyX, EmptyY, EmptyCount, OScore, XScore)

If (WinOrLoss(OScore) = 1) Or (WinOrLoss(XScore) = 1) Or (EmptyCount = 0) Then

Else

Call ComputerPlay(XScore, OScore, EmptyCount)

End If

If EmptyCount = 0 Then

UserForm1.Controls("TextBox10") = "DRAW!!!!!!!"

UserForm1.Controls("TextBox13") = UserForm1.Controls("TextBox13") + 1

UserForm1.Controls("TextBox14") = UserForm1.Controls("TextBox14") + 1

End If

End Sub

Function ExamineEachFormCell(EmptyX, EmptyY, EmptyCount, OScore, XScore)

EmptyCount = NextEmptyFormCell(EmptyX, EmptyY, OScore, XScore)

If WinOrLoss(OScore) = 1 Then

UserForm1.Controls("TextBox10") = "The COMPUTER Wins!"

UserForm1.Controls("TextBox11") = UserForm1.Controls("TextBox11") + 1

End If

If WinOrLoss(XScore) = 1 Then

UserForm1.Controls("TextBox10") = "YOU WON! Congratulations!!!"

UserForm1.Controls("TextBox12") = UserForm1.Controls("TextBox12") + 1

End If

End Function

The computer figures out which cell is empty by reviewing each cell for a value.

The function passes the number of empty cells back because this is used to know if

the game is drawn. The coordinates of the next empty cell are also passed along for

the computer to use to play its next move. If there are no more cells left, then the game

cannot be played any more—​hence drawn.